package curves.gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import curves.Point;
import curves.Surface;

public final class WeightDialog  extends JDialog {

    private JSlider slider;
    private JButton button;
    private JPanel panel;
    private JLabel label;
    private Surface surface;
    private Window window;
    private DecimalFormat df = new DecimalFormat("#.##");

    private Point point;

    public WeightDialog(Window aFrame, Surface surface, Point point) {
        super(aFrame, true);
        this.surface = surface;
        this.window = aFrame;
        this.point = point;
        
        panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        label = new JLabel("Enter desired weight:");
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(label);

        slider = new JSlider(0, 1000);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.addChangeListener(new SliderChangeListener());
        this.setSliderValue((point.getWeight()));
        
        panel.add(slider);

        button = new JButton("Ok");
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        button.addActionListener(new OkButtonListener());
        panel.add(button);

        getContentPane().add(panel);

        pack();
        setResizable(false);

    }

    public void setSliderValue(double weight){
        double y = weight * 5.0;
        y = Math.pow(y, 1.0 / 3.0);
        slider.setValue((int)(y * 100.0));
    }

    public double getSliderValue(){
        double x = slider.getValue() / 100.0;
        return x*x*x / 5.0;
    }

    @Override
    public void setVisible(boolean visible){
        setSliderValue(point.getWeight());
        this.setTitle("Weight: " + df.format(getSliderValue()));
        super.setVisible(visible);
    }

    public void setTargetPoint(Point point){
        this.point = point;
    }
    
    class OkButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            WeightDialog.this.setVisible(false);
        }
    }

    class SliderChangeListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            WeightDialog.this.setTitle("Weight: " + df.format(getSliderValue()));
            // TODO check this magic
            point.setWeight(getSliderValue());
            surface.getCurrentCurve().updateCurve(point);
            window.getGraphicEngine().repaint();
        }
    }

}
